package com.factory.test.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class GPIOFileUtil {



    public static boolean write(String filePath, String value){
        File file = new File(filePath);
        if(!file.exists()){
            return false;
        }

        OutputStreamWriter ops = null;
        try {
            ops = new OutputStreamWriter(new FileOutputStream(file));
            ops.write(value);
            ops.flush();
            return true;
        } catch (Exception e) {
            Log.e("GPIO", "write fail", e);
        } finally {
            if(ops != null){
                try {
                    ops.close();
                } catch (IOException e) {
                }
            }
        }
        return false;
    }


    public static int read(String filePath){
        File file = new File(filePath);
        if(!file.exists()){
            return -1;
        }

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line = br.readLine();
            if(line != null){
                return Integer.parseInt(line);
            }
        } catch (Exception e) {
            Log.e("GPIO", "reader fail", e);
        } finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
        }
        return -1;
    }

    public static String readString(String filePath){
        File file = new File(filePath);
        if(!file.exists()){
            return "";
        }

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line = br.readLine();
            return line;
        } catch (Exception e) {
            Log.e("GPIO", "reader fail", e);
        } finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
        }
        return "";
    }

    static void createNode(int nodeNumber){
        String path = "/sys/class/gpio/export";
        write(path, String.valueOf(nodeNumber));
    }
}
